package com.kara.woodAgent;

import com.kara.woodAgent.agent.graph.BaseGraph;
import com.kara.woodAgent.agent.graph.RunningGraph;
import com.kara.woodAgent.agent.graph.communicate.ChannelPayload;
import com.kara.woodAgent.agent.graph.communicate.StepImage;
import com.kara.woodAgent.agent.graph.communicate.TransmitPayload;
import com.kara.woodAgent.agent.wood.context.WoodContext;
import com.kara.woodAgent.agent.wood.playload.InterruptMessage;
import com.kara.woodAgent.agent.wood.playload.InterruptPayload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.util.Scanner;

@EnableAspectJAutoProxy(proxyTargetClass = true)
@SpringBootApplication
public class WoodAgentBaseApplication implements ApplicationListener<ApplicationReadyEvent> {

	public static void main(String[] args) {
		SpringApplication.run(WoodAgentBaseApplication.class, args);
	}


	@Autowired
	private BaseGraph<WoodContext> woodAgent;


	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {

		WoodContext woodContext = new WoodContext();

		woodContext.setUserQuestion("""
				请帮我打包xxl-job项目在本地,并帮我编写一个xxl-job的启动脚本,
				##### 注意: 
				xxl-job-admin修改 springboot配置文件  连接数据库: host:ip 88.70.77.80:3306   xxl_job 库   user: root password:  123456
				本地有jdk21 环境 和 maven 
				#### 要求:
				1. 你为保证 本机安全,你的所有操作都要在 /home/tzy/test_dev 目录下, 所有你创建的文件都不能超过这个目录
				2. 启动脚本前台运行,可以直接在命令行是看到输出内容
				3. 在最后请你运行脚本,检查是否能运行
				4. xxl-job 去gitee 拉去克隆
				""");
		StepImage<WoodContext> image = woodAgent.createImage(woodContext);


		boolean loop = true;
		while (loop) {

			RunningGraph<WoodContext> runningGraph = woodAgent.build(image);
			runningGraph.then((log) -> {
				System.out.println(log);
				System.out.println("------------------------------------------");
			}).start();


			if (runningGraph.checking()) {
				image = runningGraph.image();

				ChannelPayload channelPayload = image.getChannelPayload();

				if (image.subGraphCheck() && channelPayload instanceof TransmitPayload transmitPayload) {
					channelPayload = transmitPayload.basePayload();
				}

				if (channelPayload instanceof InterruptPayload interruptPayload) {

					System.err.println("========================input :======================================");
					System.err.println(interruptPayload.getMessage());

					Scanner scanner = new Scanner(System.in);
					String string = scanner.nextLine();
					InterruptMessage from = InterruptMessage.from(interruptPayload.getId(), string);
					image.setChannelMessage(from);
					System.err.println("=====================================================================");
				}

			} else {
				loop = false;
			}
		}
	}
}
